package com.biz.primus.ms.sms.service.internal;

import com.biz.primus.ms.sms.dao.po.SensitiveWordRecord;
import com.biz.primus.ms.sms.dao.repository.SensitiveWordRepository;
import com.google.common.base.Joiner;
import com.google.common.base.Optional;
import com.google.common.base.Splitter;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.Sets;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @author yanweijin
 * @date 2017/6/4
 */
@Service
public class SimpleSensitiveWordServiceImpl implements SensitiveWordService{

	@Autowired
	private SensitiveWordRepository sensitiveWordRepository;

	private final LoadingCache<String,String[]> wordsCache;

	private static final String wordCacheKey = "wordCacheKey";

	public SimpleSensitiveWordServiceImpl(long cacheExpireMilliSeconds){
		wordsCache = CacheBuilder.newBuilder().expireAfterWrite(cacheExpireMilliSeconds,TimeUnit.MILLISECONDS)
				.build(new CacheLoader<String, String[]>() {
					@Override
					public String[] load(String key) throws Exception {
						Set<String> words = findAllWords();
						return words.toArray(new String[words.size()]);
					}
				});
	}

	public SimpleSensitiveWordServiceImpl(){
		this(10000L);
	}


	@Override
	public boolean saveSensitiveWords(Set<String> words) {
		SensitiveWordRecord record = new SensitiveWordRecord();
		record.setWords(Joiner.on(',').skipNulls().join(words));
		sensitiveWordRepository.save(record);
		return true;
	}

	@Override
	public Set<String> findAllWords() {
		SensitiveWordRecord record = sensitiveWordRepository.findFirstByOrderByIdDesc();
		if(record == null){
			return Sets.newLinkedHashSet();
		}
		return Sets.newLinkedHashSet(Splitter.on(',').trimResults().split(record.getWords()));
	}

	@Override
	public Optional<String> findSensitiveWord(String text) {
		String[] words = wordsCache.getUnchecked(wordCacheKey);
		if(ArrayUtils.isEmpty(words)){
			return Optional.absent();
		}
		for (String word : words) {
			if(text.indexOf(word)!=-1){
				return Optional.of(word);
			}
		}
		return Optional.absent();
	}
}
